import './index.scss'
import TextInput, { type TextInputRef } from '../../../components/TextInput'
import { memo, useEffect, useRef, useState } from "react";
import { useAppSelector } from "../../../utils/storeHook/storeHook";
import http from "../../../utils/http";
import api from "../../../api";
import { message, Skeleton } from "antd";
import { MessageItem } from "../../../components";
import socketService from "../../../services/socketService"; // 导入服务
import { UserOutlined } from '@ant-design/icons';

interface MessageItemT{
    message_id:string,
    direct_chat_id:string,
    content:string,
    sender_id:string,
    created_at:string,
    sender_avatar:string,
    sender_name:string
}

interface directChatInfo{
    user1_id: string;
    user1_name: string;
    user2_id: string;
    user2_name: string;
    chat_id: string;
}

interface AttachmentT {
    file_id: string;
    file_url: string;
    file_name?: string;
    width?: number;
    height?: number;
    size: number;
    mime_type: string;
    alt_text?: string;
}

interface messageInpT {
    text: string;
    attachments?: AttachmentT[];
    recorder?:AttachmentT
}


const PrivateChat=memo(({chat_id}:{chat_id:string})=>{
    const [messageApi, contextHolder] = message.useMessage();
    const curUserId = useAppSelector(state=>state.auth.user_id)

    const textInpRef = useRef<TextInputRef>(null)
    const messageListRef = useRef<HTMLDivElement>(null)

    const actServerId = useAppSelector(state=>state.channel.actServerId)
    const isConnect = useAppSelector(state=>state.server.isConnect)
    const userType = useAppSelector(state=>state.auth.userType)
    
    const [isLoading,setIsloading] = useState(true)
    const [messageList,setMessageList] = useState<MessageItemT[]>([])
    const [moreMessageList,setMoreMessageList] = useState<MessageItemT[]>([])
    const [directChatInfo, setDirectChatInfo] = useState<directChatInfo|null>(null)
    const [messageFiles, setMessageFiles] = useState<{[messageId:string]:string[]}>({})
    
    const [pagigation,setPagigation] = useState({
        pageCur:1,
        pageSize:20,
        total:0
    })

    async function getPrivateMessageList(){
        await http.post(api.message.getPrivateMessageList,{chat_id:chat_id,...pagigation}).then(res=>{
            const resData = res.data
            setPagigation({...pagigation,total:resData.totalMessage})
            setMessageList(resData.messageList)
            setDirectChatInfo({...resData})
            setIsloading(false)
            resData.messageList.forEach((item:MessageItemT)=>{
                const fileList:string[] = []
                const content = JSON.parse(item.content)
                if(content.attachments.length > 0){
                    content.attachments.forEach((item:AttachmentT)=>{
                        fileList.push(item.file_id)
                    })
                }
                if(content.recorder){
                    fileList.push(content.recorder.file_id)
                }
                if(fileList.length > 0){
                    setMessageFiles(prev=>({...prev,[item.message_id]:fileList}))
                }
            })
            
        }).catch(err=>{
            messageApi.error(err.message)
            setIsloading(false)
        })
        
    }

    function getMoreMessages(){
        setPagigation({...pagigation,pageCur:pagigation.pageCur+1})
        const submit = {
            chat_id:chat_id,
            server_id:actServerId,
            userType:userType,
            pageCur:pagigation.pageCur+1,
            pageSize:pagigation.pageSize
        }
        http.post(api.message.getChannelMessageList,{...submit}).then(res=>{
            const resData = res.data
            setMoreMessageList(prev=>([...prev,...resData.messageList]))
        }).catch(err=>{
            messageApi.open({
                type:'error',
                content:err.message
            })
            setIsloading(false)
        })
    }

    function handleChange(messageInpItem:messageInpT){
        const content = JSON.stringify(messageInpItem)
        if(!chat_id) return
        socketService.sendPrivateMessage(chat_id,content).then(()=>{
            textInpRef.current?.clearInput()
            localStorage.setItem(chat_id+'msg',JSON.stringify(''))
        })
    }

    function onDeleteMsg(id:string){
        socketService.deletePrivateMessage(id)
    }

    // 处理收到的新消息
    function handleNewMessage(message: MessageItemT){
        // 转换为前端使用的消息结构
        setMessageList(prev=>[...prev, message]);
        const fileList:string[] = []
        const content = JSON.parse(message.content)
        if(content.attachments.length > 0){
            content.attachments.forEach((item:AttachmentT)=>{
                fileList.push(item.file_id)
            })
        }
        if(content.recorder){
            fileList.push(content.recorder.file_id)
        }
        if(fileList.length > 0){
            setMessageFiles(prev=>({...prev,[message.message_id]:fileList}))
        }
    };

    // 处理删除的消息
    function handleDelMessage({message_id}:{message_id:string,channel_id:string}){
        setMessageList(prev=>prev.filter(item=>item.message_id!==message_id))
        console.log(message_id,1111);
        
    };

    // 初始化Socket连接
    useEffect(() => {
        
        // 清理函数：离开频道并断开连接
        return () => {
            localStorage.removeItem(chat_id+'msg')
            if (chat_id) {
                socketService.leavePrivate(chat_id);
            }
        };
    }, []);

    // 监听频道变化/拉取频道消息
    useEffect(()=>{
        if (!chat_id || !isConnect) return;

        // 加入新频道
        socketService.joinPrivate(chat_id);
        
        // 设置消息监听器（新消息）
        socketService.onNewMessage(handleNewMessage);

        // 设置消息监听器（删除消息）
        socketService.onDelMessage(handleDelMessage);

        getPrivateMessageList()
        return () => {
            socketService.offNewMessage();
            socketService.offDelMessage();
        }
    },[chat_id,isConnect])

    useEffect(()=>{
        const scrollToNewestMsg = () => {
            if (messageListRef.current) {
                messageListRef.current.scrollTo({
                    top: messageListRef.current.scrollHeight,
                    behavior: 'smooth'
                });
            }
        };
        const timer = setTimeout(scrollToNewestMsg, 100);

        // 删除message时同步删除文件
        const messages = messageList.map(item=>item.message_id)
        Object.keys(messageFiles).forEach(key=>{ 
            if(!messages.includes(key)){
                messageFiles[key].forEach(file_id=>{
                     http.post(api.file.deleteFile,{file_id:file_id})
                })
                delete messageFiles[key]
            }
        })
        
        return () => clearTimeout(timer);
    },[messageList])

    return (
        <>
            {contextHolder}
            {isLoading&&
            <div className="skeleton"><Skeleton active paragraph={{rows:8}}></Skeleton></div>}
            <div className="privateChat_box">
                <div className="privateChat_header">
                    <div className="privateChat_title">
                        <span><UserOutlined /></span>
                        <div>{directChatInfo?.user1_id == curUserId?directChatInfo.user2_name:directChatInfo?.user1_name}</div>
                    </div>
                </div>
                <div className="privateChat_message">
                    <div className="privateChat_messageList" ref={messageListRef}>
                        {pagigation.pageCur*pagigation.pageSize<pagigation.total&&<div className="privateChat_showMore" onClick={getMoreMessages}>展开更多</div>}
                        {
                            messageList.length>0&&moreMessageList.map((item) =>
                            <div id={'MSG'+item.message_id} key={item.message_id}>
                                <MessageItem
                                    item={item} 
                                    onDelete={onDeleteMsg}
                                    id={item.message_id}
                                    isMGT={false}
                                />
                            </div>)
                        }
                        {
                            messageList.length>0&&messageList.map((item) =>
                            <div id={'MSG'+item.message_id} key={item.message_id}>
                                <MessageItem
                                    item={item} 
                                    onDelete={onDeleteMsg}
                                    id={item.message_id}
                                    isMGT={false}
                                />
                            </div>)
                        }
                    </div>
                    <div className="privateChat_message_input">
                        <TextInput
                            onChange={handleChange}
                            ref={textInpRef}
                            direct_chat_id={chat_id}
                            actions={['emotion','picture','file','recorder']}
                        ></TextInput>
                    </div>
                </div>
            </div>
        </>
    )
})

export default PrivateChat;